package models

import (
	"database/sql"
	"database/sql/driver"
	"encoding/json"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"
)

type DeletedAt sql.NullInt64

// Scan implements the Scanner interface.
func (n *DeletedAt) Scan(value interface{}) error {
	return (*sql.NullInt64)(n).Scan(value)
}

// Value implements the driver Valuer interface.
func (n DeletedAt) Value() (driver.Value, error) {
	if !n.Valid {
		return nil, nil
	}
	return n.Int64, nil
}

func (n DeletedAt) MarshalJSON() ([]byte, error) {
	if n.Valid {
		return json.Marshal(n.Int64)
	}
	return json.Marshal(nil)
}

func (n *DeletedAt) UnmarshalJSON(b []byte) error {
	if string(b) == "null" {
		n.Valid = false
		return nil
	}
	err := json.Unmarshal(b, &n.Int64)
	if err == nil {
		n.Valid = true
	}
	return err
}

func (DeletedAt) QueryClauses(f *schema.Field) []clause.Interface {
	return []clause.Interface{gorm.SoftDeleteQueryClause{Field: f}}
}

type IdModel struct {
	ID uint `gorm:"primary_key" json:"id"`
}

type CreatedAtModel struct {
	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"` // 使用时间戳秒数填充创建时间
}

type UpdatedAtModel struct {
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"` // 使用时间戳秒数填充创建时间
}

type DeletedAtModel struct {
	DeletedAt DeletedAt `gorm:"index" json:"-"`
}

type AotuTimeModel struct {
	CreatedAtModel
	UpdatedAtModel
}

type BaseModel struct {
	AotuTimeModel
	DeletedAtModel
}
